/**
 * Written by Nicholas Hillier: Nov 2008
 * 
 * NEEDS REFACTORING
 * 
 * Creates an input field accepting focus and validating a number of different types..
 * 
 * TODO: Use polymorphism to extract form field types...
 * Abstract the validate function to validate field based on type
 *  
*/
package com.ghostmonk.form
{
	import flash.display.*;
	import flash.events.FocusEvent;
	import flash.text.TextField;
	
	public class InteractiveFormField
	{
		private var _textField:TextField;
		private var _label:String;
		private var _background:DisplayObject;
		private var _alpha:Number;
		
		public function get view():TextField
		{
			return _textField;
		}
		
		public function get text():String
		{
			return _textField.text;
		}
		
		public function get alpha():Number
		{
			return _alpha;	
		}
		
		public function set alpha(value:Number):void
		{
			_alpha = value;
			_textField.alpha = _alpha;
			_background.alpha = _alpha;
		}
		
		public function InteractiveFormField(textField:TextField, background:DisplayObject, index:int, label:String)
		{
			_textField = textField;
			_background = background;
			_textField.tabIndex = index;
			_label = label;
			_textField.text = _label;
			
			activate();
		}
		
		public function selectAll(stage:Stage):void
		{
			stage.focus = _textField;
			_textField.setSelection(0,_textField.text.length);
		}
		
		public function deactivate():void
		{
			_textField.mouseEnabled = false;
			_textField.selectable = false;
			_textField.removeEventListener(FocusEvent.FOCUS_IN, onFocusIn);
			_textField.removeEventListener(FocusEvent.FOCUS_OUT, onFocusOut);
		}
		
		public function activate():void
		{
			_textField.mouseEnabled = true;
			_textField.selectable = true;
			_textField.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
			_textField.addEventListener(FocusEvent.FOCUS_OUT, onFocusOut);	
		}
		
		public function get isValid():Boolean
		{	
			return _textField.text == "" || _textField.text.substring(0,_textField.text.length) == _label ? false : true;
		}
		
		public function get isValidEmail():Boolean
		{
			var emailExpression:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
			return emailExpression.test(_textField.text);
		}
		
		public function get isValidPostalCode():Boolean
		{
			var reg:RegExp = /^([ABCEGHJ-NPRSTVXYabceghj-nprstvxy]\d[ABCEGHJ-NPRSTV-Zabceghj-nprstv-z])\ {0,1}(\d[ABCEGHJ-NPRSTV-Zabceghj-nprstv-z]\d)$/; 
			return reg.test(_textField.text);
		}
		
		public function reset():void
		{
			_textField.text = _label;
			_background.filters = [];
		}
		
		private function onFocusIn(e:FocusEvent):void
		{ 	
			_textField.text = _textField.text.substring(0,_label.length) == _label ? "" : _textField.text;
			//_background.filters = [Config.FORM_GLOW];
		}
		
		private function onFocusOut(e:FocusEvent):void
		{ 
			_textField.text = _textField.text == "" ? _label : _textField.text;
			_background.filters = [];
		}

	}
}